package com.itkf.core.lifecycle;

import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 管理整个线程池的生命周期
 */
public class DtpLifecycle implements LifecycleManager {
    /**
     * 线程池是否处于
     */
    private final AtomicBoolean isRuning = new AtomicBoolean(false);

    @Override
    public void start() {
        //添加拒绝策略后开始启动线程池
        if (this.isRuning.compareAndSet(false, true)) {
            DtpRegistry.getAllExecutor().forEach((name, executor) -> {
               // executor.init();
            });
        }
    }

    @Override
    public boolean isRuning() {
        return this.isRuning.get();
    }

    @Override
    public void stop() {
        if (this.isRuning.compareAndSet(true, false)) {
            shutdownInternal();
            DtpRegistry.getAllExecutor().forEach((name, executor) -> {
                if(executor.isWaitTime()){
                    for (Runnable remainingTask : executor.shutdownNow()) {
                        cancelRemainingTask(remainingTask);
                    }
                }else{
                    executor.shutdown();
                }

            });
        }
    }

    @Override
    public void stop(Runnable callback) {
        if (this.isRuning.compareAndSet(true, false)) {
            shutdownInternal();
        }
        callback.run();
    }

    @Override
    public void shutdownInternal() {
        //TODO  关闭线程池的守护线程和框架
    }

    //TODO 为什么会用到instanceof，有点迷
    protected static void cancelRemainingTask(Runnable task) {
        if (task instanceof Future) {
            //取消运行中的任务 Future:异步来管理线程状态
            ((Future<?>) task).cancel(true);
        }
    }
}
